Running Python in a Virtual Machine

This section covers setting up a virtual machine (a computer that is simulated inside of another computer) running Ubuntu on which we will then install Python.

If you're not familiar with terminals I would recommend looking at the Terminals and You section for a quick primer.

Background

Vagrant is a tool for managing virtual machines (VMs). A VM is a computer that is being simulated inside of another computer. When used in conjuction with Virtual Box (a piece of software that handles the simulation of the computer) it can be used to set up Python in a relatively painless manner.

Installation

Begin by installing Vagrant and Virtual Box.

Setup

Download this project from Github and navigate to the root directory (see Terminals and You for details on using terminals) of the project. The root directory contains a file named Vagrantfile that is used to tell Vagrant what kind of VM we want. Running the command

vagrant up

will create an Ubuntu VM and run the provision.sh script which will setup Python and the libraries you will need. Note that this process may take a long time and requires an internet connection.

Usage

Once the previous command completes you will be able to ssh into the VM using the command

vagrant ssh

Note that this command needs to be run from the same directory as the Vagrantfile.

From within the VM navigate to the /vagrant directory using

cd /vagrant

You will notice that this directory has the same directories and files as the one containing the Vagrantfile on the host machine (the machine running the VM). Edits made to files on the host machine will automatically be synced with those in the VM. This means that we can edit code in the host machine and run it in the VM.

Jupyter Notebooks

Vagrant can also forward ports on your host machine to the VM. This makes it possible to run a Jupyter notebook server within the VM and access it on the host machine. To start the Jupyter server use

jupyter notebook --no-browser --ip=0.0.0.0

and the go to

localhost:8888

in a browser.

Stopping the VM

When you are done using the virtual machine it is a good idea to stop it to avoid it eating up resources on the host. The command

vagrant halt

can be used for this. To use it in the future, run

vagrant up

again. Note that this will take less time than the first run as the machine will already be set up.